<template>
  <div class="home" style="padding: 20px" >
    <!--    搜索-->
    <div style="margin: 10px 0">
      <el-input v-model="search" placeholder="请输入搜索内容" style="width: 30%" />
    </div>

    <el-table :data="tableData.filter(
        (data) =>
           !search || data.name.toLowerCase().includes(search.toLowerCase())
          )" border stripe style="width: 70vw">
      <el-table-column prop="id" label="ID" sortable />
      <el-table-column prop="name" sortable label="名称"  />
      <el-table-column
              label="示例图">
        <template #default="scope">
          <el-image
                  style="width: 100px; height: 100px"
                  :src="scope.row.cover"
                  :preview-src-list="[scope.row.cover]">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="price" sortable label="价格" />
      <el-table-column prop="stock" label="库存" />
      <el-table-column prop="introduction" label="简介" >
        <template #default="scope">
          <el-button type="success" style="margin-left: 16px" @click="drawerShow(scope.row)">
            查看
          </el-button>
        </template>
      </el-table-column>
      <el-table-column width="120" label="操作">
        <template #default="scope">
          <el-button type="danger" style="margin: auto;padding-left: 10px"  @click="handleEdit(scope.row)" >
            加入购物车</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogVisible" title="请输入购买数量" width="30%">
      <el-form :model="form" label-width="120px">
        <el-form-item >
          <el-input-number v-model="form.num" :min="1" :max="maxNum" @change="handleChange" />
        </el-form-item>
      </el-form>
      <template #footer>
            <span class="dialog-footer">
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="buy">确认</el-button>
            </span>
      </template>
    </el-dialog>

    <div style="margin: 10px 0">
      <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              v-model:currentPage="currentPage"
              :page-sizes="[5, 10, 15]"
              :page-size="pageSize"
              layout="sizes, prev, pager, next, jumper"
              :total="total">
      </el-pagination>

    </div>
  </div>

  <el-drawer v-model="drawer" title="商品详情" >
    <el-descriptions
            class="margin-top"
            :column="1"
            :size="size"
            border
    >
      <el-descriptions-item>
        <template #label>
          商品名
        </template>
        {{form.name}}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          示例图
        </template>
        <el-image
                style="width: 100px; height: 100px"
                :src="form.cover"
                :preview-src-list="[form.cover]">
        </el-image>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          简介
        </template>
        {{form.introduction}}
      </el-descriptions-item>
    </el-descriptions>
  </el-drawer>

</template>

<script>
// @ is an alias to /src

import { ArrowDown,DocumentAdd,Plus } from '@element-plus/icons'
import { ElMessage } from 'element-plus'
import request from "../utils/request";
import {ref} from "vue";


export default {
  name: 'CustomMenu',
  components: {
      ArrowDown,DocumentAdd
  },
  data(){
    return{
      form:{},
      search:'',
      currentPage:1,
      total:0,
      pageSize:10,
      drawer:false,
      dialogVisible:false,
      tableData:[],
      maxNum:1,
      currentId:0,
      // filesUploadUrl: "http://" + window.server.filesUploadUrl + ":9090/files/upload",
        filesUploadUrl: "http://"+window.server.filesUploadUrl+":9090/files/upload",
    }
  },
  created() {
    let userStr = sessionStorage.getItem("user") || "{}"
    this.user = JSON.parse(userStr)
    // // 请求服务端，确认当前登录用户的 合法信息
    // request.get("/user/" + this.user.id).then(res => {
    //   if (res.code === '0') {
    //     this.user = res.data
    //   }
    // })

    this.load()
  },
  methods:
          {
            add(){
                this.dialogVisible=true
                this.form={}
                if (this.$refs['upload']) {
                  this.$refs['upload'].clearFiles()  // 清除历史文件列表
                }
            },

            buy(id) {
              console.log(this.user)
              request.get("/orderlist/buy/" + this.form.id, {
                params: {
                  amount: this.form.num,
                  userId: this.user.id,
                  username: this.user.username
                }
              })
              this.form.stock-=this.form.num
              request.put("/product",this.form).then(res=>{
                console.log(res)
                if (res.code === '0') {
                  this.$message({
                    type: "success",
                    message: "购买成功"
                  })
                } else {
                  this.$message({
                    type: "error",
                    message: res.msg
                  })
                }
                this.load()
              })
              this.dialogVisible=false
            },
            drawerShow(row){
              this.form = JSON.parse(JSON.stringify(row))
              this.drawer = true
              this.form.productid=this.form.id
              this.form.id=null
              this.form.userId=this.user.id
              this.form.username=this.user.username
              request.post("/browse",this.form).then(res=>{
                console.log(res)
                if (res.code === '0') {
                } else {
                  this.$message({
                    type: "error",
                    message: res.msg
                  })
                }
                this.load()
              })
            },
            load() {
              request.get("/product", {
                params: {
                  pageNum: this.currentPage,
                  pageSize: this.pageSize,
                  search: this.search
                }
              }).then(res => {
                this.tableData = res.data.records
                this.total = res.data.total
              })
            },

            save(){
              if(this.form.id){
                request.put("/product",this.form).then(res=>{
                    console.log(res)
                  if (res.code === '0') {
                    this.$message({
                      type: "success",
                      message: "更新成功"
                    })
                  } else {
                    this.$message({
                      type: "error",
                      message: res.msg
                    })
                  }
                  this.load()
                })
              }else
              {
                request.post("/product",this.form).then(res=>{
                    console.log(res)
                  if (res.code === '0') {
                    this.$message({
                      type: "success",
                      message: "新增成功"
                    })
                  } else {
                    this.$message({
                      type: "error",
                      message: res.msg
                    })
                  }
                  this.load()
                })
              }


              this.dialogVisible = false
            },
            handleAvatarSuccess(res, file) {
              this.imageUrl = URL.createObjectURL(file.raw)
            },
            filesUploadSuccess(res) {
              console.log(res)
              this.form.cover = res.data
            },
            handleEdit(row){
              this.form = JSON.parse(JSON.stringify(row))
              this.maxNum=row.stock
              this.form.num=1
              this.dialogVisible = true
              console.log(this.form)
            },
            handleChange(number){
              console.log(number)
              this.load()
            },
            handleSizeChange(pageSize){
              this.pageSize = pageSize
              this.load()
            },

            handleCurrentChange(pageNum){
              this.pageNum = pageNum
              this.load()
            },
          }

}
</script>


